//
//  ICMessageHelper.m
//  ICome
//
//  Created by ENN on 16/4/7.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMessageHelper.h"
#import "ICMessageFrame.h"
#import "ICMessageModel.h"
#import "ICMessageDatabase.h"
#import "ICRecordManager.h"
#import "ICMediaManager.h"
#import "ICVideoManager.h"
#import "ICFileTool.h"
#import "NSDate+Extension.h"


#define lastUpdateKey [NSString stringWithFormat:@"%@-%@",[ICUser currentUser].eId,@"LastUpdate"]
#define directLastUpdateKey [NSString stringWithFormat:@"%@-%@",[ICUser currentUser].eId,@"directLastUpdate"]

@implementation ICMessageHelper


// 创建一条本地消息
+ (ICMessageFrame *)createMessageFrame:(NSString *)type
                               content:(NSString *)content
                                  path:(NSString *)path
                                  from:(NSString *)from
                                    to:(NSString *)to
                                   lnk:(NSString *)lnk
                               fileKey:(NSString *)fileKey
                              isSender:(BOOL)isSender
              receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    ICMessage *message    = [[ICMessage alloc] init];
    message.from          = from;
    message.to            = to;
    message.fileKey       = fileKey;
    message.lnk           = lnk;
    // 我默认了一个本机的当前时间，其实没用到，成功后都改成服务器时间了
    message.date          = [ICMessageHelper currentMessageTime];
    ICMessageModel *model = [[ICMessageModel alloc] init];
    message.senderName    = [ICMessageDatabase userNameWitheId:from];
    type = [self cellTypeWithMessageType:type];
    message.type          = type;
    if ([type isEqualToString:TypeText]) {
        message.content = content;
    } else if ([type isEqualToString:TypePic]) {
        message.content = @"[图片]";
    } else if ([type isEqualToString:TypeVoice]) {
        message.content = @"[语音]";
    } else if ([type isEqualToString:TypeVideo]) {
        message.content = @"[视频]";
    } else if ([type isEqualToString:TypeRedPacket]) {
        message.content = @"[红包]";
    } else if ([type isEqualToString:TypeFile]) {
        message.content = content;
    } else if ([type isEqualToString:TypeSystem]) {
        message.content = content;
    } else {
        message.content = content;
    }
    model.isSender        = isSender;
    model.mediaPath       = path;
    if (isSender) {
        message.deliveryState = ICMessageDeliveryState_Delivering;
    } else {
        message.deliveryState = ICMessageDeliveryState_Delivered;
    }
    if (receivedSenderByYourself) { // 接收到得信息是自己发的
        message.deliveryState = ICMessageDeliveryState_Delivered;
        model.isSender        = YES;
    }
    model.message = message;
    ICMessageFrame *modelF = [[ICMessageFrame alloc] init];
    modelF.model = model;
    return modelF;
}

+ (ICMessageFrame *)createTimeMessageFrame:(NSString *)type
                                   content:(NSString *)content
                                      path:(NSString *)path
                                      from:(NSString *)from
                                        to:(NSString *)to
                                   fileKey:(NSString *)fileKey
                                  isSender:(BOOL)isSender
                  receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    ICMessage *message    = [[ICMessage alloc] init];
    message.to            = to;
    message.from          = from;
    message.fileKey       = fileKey;
    // 我默认了一个本机的当前时间，其实没用到，成功后都改成服务器时间了
    message.date          = [ICMessageHelper currentMessageTime];
    ICMessageModel *model = [[ICMessageModel alloc] init];
    type = [self cellTypeWithMessageType:type];
    message.type          = type;
    if ([type isEqualToString:TypeText]) {
        message.content = content;
    } else if ([type isEqualToString:TypePic]) {
        message.content = @"[图片]";
    } else if ([type isEqualToString:TypeVoice]) {
        message.content = @"[语音]";
    } else if ([type isEqualToString:TypeVideo]) {
        message.content = @"[视频]";
    } else if ([type isEqualToString:TypeFile]) {
        message.content = @"[文件]";
    } else if ([type isEqualToString:TypeSystem]) {
        message.content = content;
    }
    model.isSender        = isSender;
    model.mediaPath       = path;
    if (isSender) {
        message.deliveryState = ICMessageDeliveryState_Delivering;
    } else {
        message.deliveryState = ICMessageDeliveryState_Delivered;
    }
    if (receivedSenderByYourself) { // 接收到得信息是自己发的
        message.deliveryState = ICMessageDeliveryState_Delivered;
        model.isSender        = YES;
    }
    model.message = message;
    ICMessageFrame *modelF = [[ICMessageFrame alloc] init];
    modelF.model = model;
    return modelF;
}

+ (NSDictionary *)createSendParamWithMessage:(ICMessage *)message {
    if (message == nil) return nil;
    NSDictionary *param = @{@"fr":message.from,
                            @"to":message.to,
                            @"st":[NSString stringWithFormat:@"%ld",message.date],//发送时间
                            @"type":message.type,//消息类型
                            @"id":@0,//消息id 发送:(消息+时间)的MD5, 接收:消息的id
                            @"txt":message.content,//消息文本内容，其它类型的名称
                            @"key":message.fileKey==nil?@"":message.fileKey,//语音filekey、图片filekey、文件filekey
                            @"lnk":message.lnk==nil?@"":message.lnk,//连接地址URL,图片格式,文件名称
                            @"status":@""//消息状态
                            };
    return param;
}


+ (NSDictionary *)createCollectMessage:(NSString *)type
                                   eId:(NSString *)eId
                                   gId:(NSString *)gId
                               photoId:(NSString *)photoId
                                 msgId:(NSString *)msgId
                                 title:(NSString *)title
                                   txt:(NSString *)txt
                                   key:(NSString *)key
                                   lnk:(NSString *)lnk {
    
    NSString *msgType;
    if ([type isEqualToString:TypeText]) {
        msgType      = @"1";
    } else if ([type isEqualToString:TypePic]) {
        msgType      = @"3";
    } else if ([type isEqualToString:TypeVoice]) {
        msgType      = @"2";
    } else if ([type isEqualToString:TypeVideo]) {
        msgType      = @"4";
    } else if ([type isEqualToString:TypeFile]) {
        msgType      = @"5";
    } else if ([type isEqualToString:TypeTextURL]) {
        msgType      = @"6";
    } else if ([type isEqualToString:TypePicText]) {
        msgType      = @"7";
    } else if ([type isEqualToString:TypeDrtNews]) {
        msgType      = @"9";
    } else {
        msgType      = @"1";
    }
    
    NSDictionary *param = @{@"eId":eId,
                            @"gId":gId,
                            @"photoId":photoId == nil ? @"" :photoId,
                            @"msgId":msgId,
                            @"title":title,
                            @"txt":txt == nil ? @"" : txt,
                            @"type":msgType,
                            @"key":key == nil ? @"" : key,
                            @"lnk":lnk == nil ? @"" : lnk};
    return param;
}


/**
 *  创建一条发送消息
 *
 *  @param messageF  ---
 *  @param type    消息类型
 *  @param content 消息文本内容，其它类型的类型名称:[图片]
 *  @param fileKey 音频文件的fileKey
 *  @param from    发送者
 *  @param to      接收者
 *  @param lnk     连接地址URL,图片格式,文件名称 （目前没用到）
 *  @param status  消息状态 （目前没用到）
 *
 *  @return 发送的消息
 */
+ (ICMessage *)createSendMessageF:(ICMessageFrame *)messageF
                          Message:(NSString *)type
                          content:(NSString *)content
                          fileKey:(NSString *)fileKey
                             from:(NSString *)from
                               to:(NSString *)to
                              lnk:(NSString *)lnk
                           status:(NSString *)status
{
    ICMessage *message    = [[ICMessage alloc] init];
    message.from          = from;
    message.to            = to;
    message.content       = content;
    message.fileKey       = fileKey;
    message.lnk           = lnk;
    if ([type isEqualToString:TypeText]) {
        message.type      = @"1";
    } else if ([type isEqualToString:TypePic]) {
        message.type      = @"3";
    } else if ([type isEqualToString:TypeVoice]) {
        message.type      = @"2";
    } else if ([type isEqualToString:TypeVideo]) {
        message.type      = @"4";
    } else if ([type isEqualToString:TypeFile]) {
        message.type      = @"5";
    } else if ([type isEqualToString:TypeTextURL]) {
        message.type      = @"6";
    } else if ([type isEqualToString:TypePicText]) {
        message.type      = @"7";
    }else if ([type isEqualToString:TypeDrtNews]) {
        message.type      = @"9";
    }else if ([type isEqualToString:TypeRedPacket]) {
        message.type      = @"20";
    } else if ([type isEqualToString:TypeAtText]) {
        message.type      = @"13";
    } else if ([type isEqualToString:TypeVideoConference]) {
        message.type      = @"27";
    } else {
        message.type      = type;
    }
    if (![ICTools stringEmpty:messageF.model.message.messageId]) { // 重发的消息
        message.messageId = messageF.model.message.messageId;
        message.localMsgId = message.messageId;
        message.date = [ICMessageHelper currentMessageTime];
    } else { // 正常的新消息
        message.messageId     = [self localMessageId:content];
        message.localMsgId    = message.messageId;
        message.date          = [ICMessageHelper currentMessageTime];
    }
    return message;
}

// 时间和内容的MD5串
+ (NSString *)localMessageId:(NSString *)content
{
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yyyy-MM-dd HH:mm:ss:SSS"];
    NSString *datestr = [dateFormater stringFromDate:[NSDate date]];
    NSString *tex = content;
    NSString *idstr = [NSString stringWithFormat:@"%@%@", tex,datestr];
    NSString *pathId = [ICMD5 md5:idstr];
    return pathId;
}

// 获取语音消息时长
+ (CGFloat)getVoiceTimeLengthWithPath:(NSString *)path
{
    AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
    CMTime audioDuration = audioAsset.duration;
    CGFloat audioDurationSeconds =CMTimeGetSeconds(audioDuration);
    return audioDurationSeconds;
}

// 图片按钮在窗口中得位置
+ (CGRect)photoFramInWindow:(UIButton *)photoView
{
    return [photoView convertRect:photoView.bounds toView:[UIApplication sharedApplication].keyWindow];
}

// 放大后的图片按钮在窗口中的位置
+ (CGRect)photoLargerInWindow:(UIButton *)photoView
{
    //    CGSize imgSize     = photoView.imageView.image.size;
    CGSize  imgSize    = photoView.currentBackgroundImage.size;
    CGFloat appWidth   = [UIScreen mainScreen].bounds.size.width;
    CGFloat appHeight  = [UIScreen mainScreen].bounds.size.height;
    CGFloat height     = imgSize.height / imgSize.width * appWidth;
    CGFloat photoY     = 0;
    if (height < appHeight) {
        photoY         = (appHeight - height) * 0.5;
    }
    return CGRectMake(0, photoY, appWidth, height);
}

// 根据消息类型得到cell的标识
+ (NSString *)cellTypeWithMessageType:(NSString *)type
{
    if ([type isEqualToString:@"1"]) {
        return TypeText;
    } else if ([type isEqualToString:@"2"]) {
        return TypeVoice;
    } else if ([type isEqualToString:@"3"]) {
        return TypePic;
    } else if ([type isEqualToString:@"4"]) {
        return TypeVideo;
    } else if ([type isEqualToString:@"5"]) {
        return TypeFile;
    } else {
        return type;
    }
}


+ (BOOL)isSenderBySelf:(NSString *)from
{
    if ([from isEqualToString:[ICUser currentUser].eId]) {
        return YES;
    }
    return NO;
}


+ (ICMessageFrame *)receivedTextMessage:(NSDictionary *)dic
               receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    ICMessageFrame *messageF        = [ICMessageHelper createMessageFrame:TypeText
                                                                  content:[dic objectForKey:@"txt"]
                                                                     path:nil
                                                                     from:[dic objectForKey:@"fr"]
                                                                       to:[dic objectForKey:@"to"]
                                                                      lnk:[dic objectForKey:@"lnk"]
                                                                  fileKey:[dic objectForKey:@"key"]
                                                                 isSender:NO
                                                 receivedSenderByYourself:receivedSenderByYourself];
    // 存服务器的时间
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.messageId = [dic objectForKey:@"id"];
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    return messageF;
}

+ (ICMessageFrame *)receivedMessage:(NSDictionary *)dic
                               Type:(NSString *)type
                     receivedSender:(BOOL)receivedSender
{
    ICMessageFrame *messageF        = [ICMessageHelper createMessageFrame:type
                                                                  content:[dic objectForKey:@"txt"]
                                                                     path:nil
                                                                     from:[dic objectForKey:@"fr"]
                                                                       to:[dic objectForKey:@"to"]
                                                                      lnk:[dic objectForKey:@"lnk"]
                                                                  fileKey:[dic objectForKey:@"key"]
                                                                 isSender:NO
                                                 receivedSenderByYourself:receivedSender];
    // 存服务器的时间
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.messageId = [dic objectForKey:@"id"];
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    return messageF;
}



+ (void)receivedVoiceMessage:(NSDictionary *)dic
                      finish:(Finish)finish
    receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    NSString *fileKey   = [dic objectForKey:@"key"];
    NSString *from      = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    if (!fileKey) return;
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVoice
                                                           content:nil
                                                              path:@""
                                                              from:from
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:fileKey
                                                          isSender:NO receivedSenderByYourself:receivedSenderByYourself];
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.messageId = messageId;
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    if (finish) finish(messageF);
    
    [[ICNetworkManager sharedInstance] downloadRecod:fileKey fileDir:kAudioPath progress:^(NSProgress *pro) {
      
    } success:^(NSString *filePath) {

    } failure:^(NSError *error) {
        NSLog(@"error reason %@", error.domain);
    }];
}

// receive image message
+ (void)receivedImageMessage:(NSDictionary *)dic
                      finish:(Finish)finish
    receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    NSString *fileKey = [dic objectForKey:@"key"];
    NSString *from    = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    if (!fileKey) return;
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePic
                                                           content:nil
                                                              path:@""
                                                              from:from
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:fileKey
                                                          isSender:NO
                                          receivedSenderByYourself:receivedSenderByYourself];
    NSInteger date                     = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date        = date;
    messageF.model.message.messageId   = messageId;
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    if (finish) finish(messageF);
}

// receive video message
+ (void)receivedVideoMessage:(NSDictionary *)dic
                      finish:(Finish)finish
    receivedSenderByYourself:(BOOL)receivedSenderByYourself
                    progress:(void(^)(NSProgress *pro))progress
{
    NSString *fileKey   = [dic objectForKey:@"key"];
    NSString *from      = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    if (!fileKey) return;
    [[ICNetworkManager sharedInstance] getVideo:fileKey progress:^(NSProgress *pro) {
        progress(pro);
    } success:^(id object) {
        NSString *mp4Path = object;
        ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVideo
                                                               content:nil
                                                                  path:mp4Path
                                                                  from:from
                                                                    to:[dic objectForKey:@"to"]
                                                                   lnk:[dic objectForKey:@"lnk"]
                                                               fileKey:fileKey
                                                              isSender:NO
                                              receivedSenderByYourself:receivedSenderByYourself];
        NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
        messageF.model.message.date      = date;
        messageF.model.message.messageId = messageId;
        if (finish) finish(messageF);
    } failure:^(NSError *error) {
        NSLog(@"receivedVideoMessage-error:%@",error);
    }];
}

+ (void)receivedVideoImageMessage:(NSDictionary *)dic
                           finish:(Finish)finish
         receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    // 以视频的fileKey存储图片，而不是以图片本身的imgKey存储，做到统一
    __block NSString *fileKey   = [dic objectForKey:@"key"];
    NSString *from      = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    if (!fileKey) return;
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeVideo
                                                           content:nil
                                                              path:@""
                                                              from:from
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:fileKey
                                                          isSender:NO
                                          receivedSenderByYourself:receivedSenderByYourself];
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.messageId = messageId;
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    if (finish) finish(messageF);
}


+ (void)receivedFileMessage:(NSDictionary *)dic
                     finish:(Finish)finish
   receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    NSString *fileKey   = [dic objectForKey:@"key"];
    NSString *from      = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    NSString *lnk       = [dic objectForKey:@"lnk"];
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeFile
                                                           content:[dic objectForKey:@"txt"]
                                                              path:nil
                                                              from:from
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:fileKey
                                                          isSender:NO
                                          receivedSenderByYourself:receivedSenderByYourself];
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.lnk       = lnk;
    messageF.model.message.messageId = messageId;
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    if (finish) finish(messageF);
}


// receive system message
+ (ICMessageFrame *)receivedSystemMessage:(NSDictionary *)dic
{
    NSString *txt = [dic objectForKey:@"txt"];
    NSMutableArray *reguleStrArray = [txt regularExpressionStr];  // eId
    __block NSString *reguleStr = nil;
    if ([reguleStrArray count] == 0) {
        reguleStr = txt;
    } else { // 需要进行替换
        reguleStr = txt;
        for (NSString *obj in reguleStrArray) {
            NSString *nName = [ICMessageDatabase nickNameWithEid:obj gId:[dic objectForKey:@"to"]];
            NSString *orgstr = [NSString stringWithFormat:@"[(eId=%@)]",obj];
            if (nName == nil){ // 去拿eName
                nName = [ICMessageDatabase getUserNameWithEId:obj];
            }
            reguleStr = [reguleStr stringByReplacingOccurrencesOfString:orgstr withString:nName];
        }
    }
    
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypeSystem
                                                           content:reguleStr
                                                              path:nil
                                                              from:[dic objectForKey:@"fr"]
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:nil
                                                          isSender:NO
                                          receivedSenderByYourself:NO];
    NSInteger date                   = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date      = date;
    messageF.model.message.messageId = [dic objectForKey:@"id"];
    return messageF;
}

+ (void)receivedPicTextMessage:(NSDictionary *)dic
                        finish:(Finish)finish
      receivedSenderByYourself:(BOOL)receivedSenderByYourself
{
    NSString *fileKey   = [dic objectForKey:@"key"];
    NSString *from      = [dic objectForKey:@"fr"];
    NSString *messageId = [dic objectForKey:@"id"];
    NSString *lnk       = [dic objectForKey:@"lnk"];
    
    ICMessageFrame *messageF = [ICMessageHelper createMessageFrame:TypePicText
                                                           content:[dic objectForKey:@"txt"]
                                                              path:nil
                                                              from:from
                                                                to:[dic objectForKey:@"to"]
                                                               lnk:[dic objectForKey:@"lnk"]
                                                           fileKey:fileKey
                                                          isSender:NO
                                          receivedSenderByYourself:receivedSenderByYourself];
    NSInteger date  = [[dic objectForKey:@"st"] integerValue];
    messageF.model.message.date = date;
    
    messageF.model.message.lnk = lnk;
    messageF.model.message.messageId = messageId;
    messageF.model.message.status    = [[dic objectForKey:@"status"] intValue];
    if (finish) finish(messageF);
}

+ (NSNumber *)getLastUpdate
{
    NSNumber *lastUpdate = [[NSUserDefaults standardUserDefaults] objectForKey:lastUpdateKey];
    if (lastUpdate) {
        return lastUpdate;
    } else {
        return @0;
    }
}

+ (void)setLastUpdate:(NSNumber *)lastUpdate
{
    [[NSUserDefaults standardUserDefaults] setObject:lastUpdate forKey:lastUpdateKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSNumber *)getGroupInfoLastUpdate:(NSString *)gId
{
    return [ICMessageDatabase groupInfoLastUpdate:gId];
}

+ (void)setGroupInfoLastUpdate:(NSNumber *)lastUpdate
                           gId:(NSString *)gId
{
    [ICMessageDatabase setGroupInfoLastUpdate:gId lastUpdate:lastUpdate];
}

+ (NSNumber *)getDirectLastUpdate
{
    NSNumber *lastUpdate = [[NSUserDefaults standardUserDefaults] objectForKey:directLastUpdateKey];
    if (lastUpdate) {
        return lastUpdate;
    } else {
        return @0;
    }
}

+ (void)setDirectLastUpdate:(NSNumber *)lastUpdate
{
    [[NSUserDefaults standardUserDefaults] setObject:lastUpdate forKey:directLastUpdateKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}





// 删除消息附件
+ (void)deleteMessage:(ICMessageModel *)messageModel
{
    // 这里还是有问题的，我应该重新写出来路径的，mediaPath不是固定的路径
    // 不过先这样，不影响具体功能
    if ([ICFileTool fileExistsAtPath:messageModel.mediaPath]) {
        [ICFileTool removeFileAtPath:messageModel.mediaPath];
    }
}

// current message time
+ (NSInteger)currentMessageTime
{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSInteger iTime     = (NSInteger)(time * 1000);
    return iTime;
}

// time format
+ (NSString *)timeFormatWithDate:(NSInteger)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];//HH:mm
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
    NSString *date = [formatter stringFromDate:currentDate];
    return date;
}

+ (NSString *)timeFormatWithDate3:(NSInteger)time
{
    NSDate *createDate = [NSDate dateWithTimeIntervalInMilliSecondSince1970:(NSTimeInterval)time];
    NSString * date = [createDate formattedTime];
    return date;
}

+ (NSString *)timeFormatWithDate2:(NSInteger)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
    NSString *date = [formatter stringFromDate:currentDate];
    return date;
    
}
// time format
+ (NSString *)timeFormatWithDate4:(NSInteger)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];//HH:mm
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
    NSString *date = [formatter stringFromDate:currentDate];
    return date;
}

// update group read
+ (void)updateGroupReadWithGroupId:(NSString *)gId
{
    // 更新消息已读数
    NSNumber *localIndex   = [NSNumber numberWithInteger:[ICMessageDatabase maxMessageId:gId]];
    if ([localIndex integerValue] == 0) {
        return;
    }
    NSDictionary *param = @{
                            @"gId":gId,
                            @"localIndex":localIndex
                            };
    [[ICSocketRequestManager sharedInstance] groupReadWithObject:param Success:^(id object) {
        NSLog(@"更新已读成功");
    } Failure:^(NSError *error, id other) {
        NSLog(@"groupReadAPI request error :%@",error);
    }];
}

+ (void)updateGroupReadWithGroupId:(NSString *)gId message:(NSNumber *)messageId
{
    if([messageId integerValue] == 0)return;
    NSDictionary *param = @{
                            @"gId":gId,
                            @"localIndex":messageId
                            };
    [[ICSocketRequestManager sharedInstance] groupReadWithObject:param Success:^(id object) {
    } Failure:^(NSError *error, id other) {
        NSLog(@"groupReadAPI request error :%@",error);
    }];
}

+ (void)voiceDidRead:(NSString *)gId messageId:(NSString *)msgId
{
    if (msgId == nil) return;
    NSDictionary *parmar = @{
                             @"gId"   : gId,
                             @"msgId" : msgId
                             };
    [[ICSocketRequestManager sharedInstance] voiceReadWithObject:parmar Success:^(id object) {
    } Failure:^(NSError *error, id other) {
        NSLog(@"voiceDidRead error");
    }];
}

// 根据消息体进行存储
+ (void)messageTypeWithMessage:(NSDictionary *)dic
                      finished:(Finish)finished
{
    @try {
        NSString *type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"type"]];
        NSString *from = [NSString stringWithFormat:@"%@",[dic objectForKey:@"fr"]];
        if ([type isEqualToString:@"1"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedTextMessage:dic
                                                   receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"2"]) {
            [ICMessageHelper receivedVoiceMessage:dic finish:^(ICMessageFrame *messageF) {
                if(finished) finished(messageF);
            } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
        } else if ([type isEqualToString:@"3"]) {
            [ICMessageHelper receivedImageMessage:dic finish:^(ICMessageFrame *messageF) {
                if(finished) finished(messageF);
            } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
        } else if ([type isEqualToString:@"4"]) {
            [ICMessageHelper receivedVideoImageMessage:dic finish:^(ICMessageFrame *messageF) {
                if (finished) finished(messageF);
            } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
        } else if ([type isEqualToString:@"5"]) {
            [ICMessageHelper receivedFileMessage:dic finish:^(ICMessageFrame *messageF) {
                if (finished) finished(messageF);
            } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
        } else if ([type isEqualToString:@"0"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedSystemMessage:dic];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"6"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeTextURL
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"7"]) {
            [ICMessageHelper receivedPicTextMessage:dic finish:^(ICMessageFrame *messageF) {
                if (finished) finished(messageF);
            } receivedSenderByYourself:[ICMessageHelper isSenderBySelf:from]];
        } else if ([type isEqualToString:@"9"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeDrtNews
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"50"]) { // 机会
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeChance
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"12"]) { //
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeNotif
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"10"] || [type isEqualToString:@"11"]) { // 待办
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypePending
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"20"]) { // 红包
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeRedPacket
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"13"]) { // @功能
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeAtText
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"14"]) { // 机器人提示功能
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeQuestion
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"27"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeVideoConference
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"28"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeActivity
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else if ([type isEqualToString:@"29"]) {
            ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                   Type:TypeSysTop
                                                         receivedSender:[ICMessageHelper isSenderBySelf:from]];
            if(finished) finished(messageF);
        } else {
            
            // 用于动态注册
            NSArray *cellClassList =[[NSUserDefaults standardUserDefaults] valueForKey:@"cellClassList"];
            NSMutableArray *ids = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in cellClassList) {
                NSString *class = dict[@"class"];
                NSString *identifier = dict[@"id"];
                if (![ICTools stringEmpty:class] && ![ICTools stringEmpty:identifier]) {
                    [ids addObject:identifier];
                }
            }
            
            //  暂不支持
            if ([ids containsObject:type]) {
                ICMessageFrame *messageF = [ICMessageHelper receivedMessage:dic
                                                                       Type:type
                                                             receivedSender:[ICMessageHelper isSenderBySelf:from]];;
                if(finished) finished(messageF);
            } else {
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
                [dict setValue:@"该版本暂不支持此消息类型" forKey:@"txt"];
                ICMessageFrame *messageF = [ICMessageHelper receivedSystemMessage:[dict copy]];
                if(finished) finished(messageF);
            }
        }
        
    } @catch (NSException *exception) {
        ALERT(exception.reason);
    } @finally {
        
    }
}


+ (NSDictionary *)fileTypeDictionary
{
    NSDictionary *dic = @{
                          @"mp3":@1,@"mp4":@2,@"mpe":@2,@"docx":@5,
                          @"amr":@1,@"avi":@2,@"wmv":@2,@"xls":@6,
                          @"wav":@1,@"rmvb":@2,@"mkv":@2,@"xlsx":@6,
                          @"mp3":@1,@"rm":@2,@"vob":@2,@"ppt":@7,
                          @"aac":@1,@"asf":@2,@"html":@3,@"pptx":@7,
                          @"wma":@1,@"divx":@2,@"htm":@3,@"png":@8,
                          @"ogg":@1,@"mpg":@2,@"pdf":@4,@"jpg":@8,
                          @"ape":@1,@"mpeg":@2,@"doc":@5,@"jpeg":@8,
                          @"gif":@8,@"bmp":@8,@"tiff":@8,@"svg":@8
                          };
    return dic;
}

+ (NSNumber *)fileType:(NSString *)type
{
    NSDictionary *dic = [self fileTypeDictionary];
    return [dic objectForKey:type];
}

+ (UIImage *)allocationImage:(ICFileType)type
{
    switch (type) {
        case ICFileType_Audio:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_audio"];
            break;
        case ICFileType_Video:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_video"];
            break;
        case ICFileType_Html:
            return [UIImage imageNamedFromiComeSDKBundle:@"html"];
            break;
        case ICFileType_Pdf:
            return  [UIImage imageNamedFromiComeSDKBundle:@"icon_type_pdf"];
            break;
        case ICFileType_Doc:
            return  [UIImage imageNamedFromiComeSDKBundle:@"icon_type_word"];
            break;
        case ICFileType_Xls:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_excel"];
            break;
        case ICFileType_Ppt:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_ppt"];
            break;
        case ICFileType_Img:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_photo"];
            break;
        case ICFileType_Txt:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_txt"];
            break;
        default:
            return [UIImage imageNamedFromiComeSDKBundle:@"icon_type_file"];
            break;
    }
}


+ (NSString *)timeDurationFormatter:(NSUInteger)duration
{
    float M = duration/60.0;
    float S = duration - (int)M * 60;
    NSString *timeFormatter = [NSString stringWithFormat:@"%02.0lf:%02.0lf",M,S];
    return  timeFormatter;
    
}


// 过渡版本处理 - 直接通过ICMessage 转 各种界面需要使用到的模型
+ (ICGtasksModel *)getGtasksModelWith:(ICMessage *)message {
    ICGtasksModel *model = [[ICGtasksModel alloc] init];
    NSDictionary *fileKeyDict = [NSDictionary dictionaryWithJsonString:message.fileKey];
    model.fr = message.from;
    model.msgId = message.messageId;
    model.summary = fileKeyDict[@"summary"];
    model.title = fileKeyDict[@"title"];
    model.confirmurl = fileKeyDict[@"confirmurl"];
    model.rejecturl = fileKeyDict[@"rejecturl"];
    model.openurl = fileKeyDict[@"openurl"];
    model.status = [NSString stringWithFormat:@"%u", message.status];
    model.hide = 0;
    model.st = message.date;
    return model;
}

+ (ICChnModel *)getChnModelModelWith:(ICMessage *)message {
    ICChnModel * model = [ICChnModel mj_objectWithKeyValues:[NSDictionary dictionaryWithJsonString:message.fileKey]];
    model.time = [ICMessageHelper timeFormatWithDate2:message.date];
    model.status = message.status;
    model.hideTime = YES;
    return model;
}

+ (ICNotify *)getNotifyModelModelWith:(ICMessage *)message {
    ICNotify *model = [[ICNotify alloc] init];
    NSDictionary *fileKeyDict = [NSDictionary dictionaryWithJsonString:message.fileKey];
    model.title = message.content;
    model.messageId = message.messageId;
    model.summary = fileKeyDict[@"summary"];
    model.url = fileKeyDict[@"url"];
    model.content = fileKeyDict[@"content"];
    model.showIcon = [fileKeyDict[@"showIcon"] intValue];
    model.st = message.date;
    model.status = message.status;
    model.fr = message.from;
    return model;
}

+ (void)setServeGroupActive:(NSString *)gId {
    if ([gId hasPrefix:@"rbt"] && ![gId isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) {
        NSString *svr = [NSString stringWithFormat:@"svr_%@",[ICUser currentUser].eId];
        [ICMessageDatabase changeGroupLocalType:YES GroupId:svr];
    }
}
// 判断是否为本地的客服组
+ (BOOL)isServeRbtGroup:(NSString *)gId gType:(NSString *)gType {
    if ([gType isEqualToString:[NSString stringWithFormat:@"%d", ICGroup_ROBOT]]) { // 精灵组
        if (![gId isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) { // 非自己的精灵组
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

+ (BOOL)isUserRbtGroup:(NSString *)gId gType:(NSString *)gType {
    if ([gType isEqualToString:[NSString stringWithFormat:@"%d", ICGroup_ROBOT]]) { // 精灵组
        if ([gId isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) { // 自己的精灵组
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}


//判断
+(void)validateUrl:(NSString *)urlstr {
    if (![ICTools stringEmpty:urlstr] && ![ICTools stringEmpty:[ICTools getJSTicket]]) {
        [ICJSBridgeTools appendUserInfoforJSURL:urlstr];
    }
    NSURL *URL = [NSURL URLWithString:[urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [request setHTTPMethod:@"HEAD"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"error %@",error);
        if (error) {
            NSLog(@"不可用");
        }else{
            NSLog(@"可用");
        }
    }];
    [task resume];
}

+ (void)changeGroupStatus:(id)message {
    NSString *type = [NSString stringWithFormat:@"%@",[message objectForKey:@"type"]];
    if ([type isEqualToString:@"13"]) { // @功能
        NSDictionary *key = [NSDictionary dictionaryWithJsonString:[message objectForKey:@"key"]];
        if (![ICTools stringEmpty:key[[ICUser currentUser].eId]]) {
            [ICMessageDatabase updateGroupAlertStatus:1 gId:[message objectForKey:@"to"]];
        }
    }
}

@end
